<template>
    <div class="login-box">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <div class="title">
                管理系统
            </div>
            <div class="box">
                <el-form-item label="账号" prop="age">
                    <el-input v-model.number="ruleForm.age" />
                </el-form-item>

                <el-form-item label="密码" prop="pass">
                    <el-input v-model="ruleForm.pass" type="password" show-password />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </div>

        </el-form>
    </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { AdminLogin } from '@/api';
import { useRouter } from 'vue-router';
import { useUserinfoStore } from '@/stores';


const store = useUserinfoStore()
const router = useRouter()
const ruleFormRef = ref()

const checkAge = (rule: any, value: any, callback: any) => {
    if (value === '') {
        return callback(new Error('请输入账号'))
    } else {
        callback()
    }
}

const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    pass: '',
    age: '',
})

const rules = reactive({
    age: [{ validator: checkAge, trigger: 'blur' }],
    pass: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = (formEl: any) => {
    if (!formEl) return
    formEl.validate(async (valid: any) => {
        if (valid) {//表单验证通过
            const res = await AdminLogin({ adminname: ruleForm.age, password: ruleForm.pass }) as any
            if (res.code === '200') {
                console.log(res);
                store.setUserToken(res.data.token)
                localStorage.setItem('Token', res.data.token)
                router.push('/home')
            }
        } else {
            return false
        }
    })
}

const resetForm = (formEl: any) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.login-box {
    position: relative;
    height: 100%;
    background: url("@/assets/1.jpg");
    background-size: cover;
}

.demo-ruleForm {
    padding: 30px;
    height: 300px;
    width: 30%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid gray;
    background: rgba($color: #e6b8de, $alpha: 0.5);
    border-radius: 5%;
    box-shadow: 10px;
    color: red;

    .title {
        font-size: 30px;
        font-family: 楷体;
        text-align: center;
    }

    .box {
        margin-top: 50px;
        margin-right: 50px;
    }
}
</style>